package com.feihao.zhou.service.impl;

import com.feihao.zhou.DBUtils.DaoFactory;
import com.feihao.zhou.DBUtils.TransactionUtil;
import com.feihao.zhou.bean.Dept;
import com.feihao.zhou.dao.DeptDao;
import com.feihao.zhou.service.DeptService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class DeptServiceImpl implements DeptService {
    @Override
    public void addDept(Dept dept) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DaoFactory.getSqlSession();
            DeptDao mapper = DaoFactory.getMapper(sqlSession, DeptDao.class);
            mapper.addDept(dept);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }

    @Override
    public List<Dept> findAll() {
        List<Dept> all = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = DaoFactory.getSqlSession();
            DeptDao mapper = DaoFactory.getMapper(sqlSession, DeptDao.class);
            all = mapper.findAll();
            return all;
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        } finally {
            TransactionUtil.close(sqlSession);
        }
        return null;
    }

    @Override
    public Dept findById(String id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DaoFactory.getSqlSession();
            DeptDao mapper = DaoFactory.getMapper(sqlSession, DeptDao.class);
            Dept byId = mapper.findById(id);
            return byId;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionUtil.rollback(sqlSession);
        } finally {
            TransactionUtil.close(sqlSession);
        }
        return null;
    }

    @Override
    public void updateDept(Dept dept) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DaoFactory.getSqlSession();
            DeptDao mapper = DaoFactory.getMapper(sqlSession, DeptDao.class);
            mapper.updateDept(dept);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionUtil.rollback(sqlSession);
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }

    @Override
    public void deleteDept(String id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DaoFactory.getSqlSession();
            DeptDao mapper = DaoFactory.getMapper(sqlSession, DeptDao.class);
            mapper.deleteDept(id);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionUtil.rollback(sqlSession);
        } finally {
            TransactionUtil.close(sqlSession);
        }
    }
}
